<template>
  <div class="app-container">
    <el-dialog :visible.sync="dialogParameters"
               width="50%"
               title="配置角色各个功能参数">
      <el-card v-for="item in callGetMenuTreeParameters()"
               :key="item.id"
               shadow="never"
               class="el-card-param">
        <div slot="header"
             class="clearfix">
          <el-row>
            <el-col :span="6">
              <span>{{item.title}}</span>
            </el-col>
            <el-col :span="18">
              <span>{{item.remark}}</span>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-form label-width="100px"
                   :disabled="dialogParametersDisable">
            <el-form-item v-for="param in item.parameters"
                          :key="param.parameterId"
                          label-width="150px"
                          :label="getParameterTitle(param.parameterId)"
                          class="el-form-item-param"
                          style="margin-top:-5px; ">
              <!-- {{ getDictLabel('mandy_param', param.parameterId + '') }} -->
              <!-- {{ getDictLabel("mandy_param", "1") }} -->
              <el-row>
                <el-col :span="16">
                  <el-select v-model="param.value"
                             style="width:100%;"
                             clearable>
                    <el-option v-for="el_select_item 
                                                 in getParameterOptions(param.parameterId)"
                               :key="el_select_item.value"
                               :label="el_select_item.label"
                               :value="el_select_item.value" />
                  </el-select>
                </el-col>
                <el-col :span="2">
                </el-col>
                <el-col :span="6"
                        style="float: right;"
                        v-if="param.value === undefined || param.value === ''">
                  缺省值 {{getParameterDefaultValueLabel(param.parameterId)}}
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-dialog>
    <transition name="el-zoom-in-top">
      <el-card v-if="showDetail"
               shadow="hover">
        <div slot="header">
          <el-row>
            <el-col :span="10">
              <span>{{currentRole.title}}</span>
            </el-col>
            <el-col :span="4"
                    style=" text-align: center">
              <span>状态:{{ getDictLabel('audit_state', currentRole.auditState)}}</span>
            </el-col>
            <el-col :span="10">
              <!-- <el-button style="float: right; padding: 5px 15px"
                         type="text">更多 ></el-button> -->
              <el-button style="float: right; padding: 5px 5px"
                         type="text"
                         v-show="activeStep === 2"
                         @click="quitEdit">退出</el-button>
              <el-button style="float: right; padding: 5px 5px"
                         type="text"
                         v-if="hasPermission('/sysadmin/role/disable')"
                         v-show="activeStep === 2 && currentRole.auditState !=='0'"
                         @click="handleDisableRole">禁用</el-button>
              <el-button style="float: right; padding: 5px 5px"
                         type="text"
                         v-if="hasPermission('/sysadmin/role/enable')"
                         v-show="activeStep === 2 && currentRole.auditState ==='0'"
                         @click="handleEnableRole(0)">启用</el-button>
              <el-button style="float: right; padding: 5px 5px"
                         type="text"
                         v-if="hasPermission('/sysadmin/role/enable')"
                         v-show="activeStep === 2 && currentRole.auditState ==='2'"
                         @click="handleEnableRole(1)">启用新菜单</el-button>
            </el-col>
          </el-row>
        </div>

        <div v-if="activeStep===1">
          <el-row>
            <el-col :span="10">
              <el-card shadow="never"
                       class="my-contain-card">
                <div slot="header"
                     class="clearfix">
                  <span>
                    <el-row>
                      <el-col :span="12">
                        当前权限
                      </el-col>
                      <el-col :span="12">
                        <el-button style="float: right; padding: 3px 5px"
                                   type="text"
                                   @click="commitNewCandidate">提交保存</el-button>
                        <el-button style="float: right; padding: 3px 5px"
                                   type="text"
                                   @click="handleParameterSetting(1)">参数配置</el-button>
                        <el-button style="float: right; padding: 3px 5px"
                                   type="text"
                                   @click="quitEdit">取消</el-button>
                      </el-col>
                    </el-row>
                  </span>
                </div>
                <el-scrollbar style="height:580px">
                  <el-tree :data="menuTreeData"
                           style="height: 100%"
                           show-checkbox
                           node-key="id"
                           :default-expand-all="true"
                           :highlight-current="true"
                           :expand-on-click-node="false"
                           :check-strictly="true"
                           :default-checked-keys="menuTreeDataCheckedKeys"
                           ref="menuTree"
                           @current-change="menuTreeCurrentChange"
                           :props="defaultProps">
                    <span class="custom-tree-node"
                          slot-scope="{node,data}">
                      <span>
                        <i :class="data.iconClass"></i>
                        {{ node.label }}</span>
                      <!-- <span v-if="data.hasParameter === '1'"> -->
                      <span v-if="data.permType === '0' && data.parameters.length > 0 ">
                        <el-button type="text"
                                   size="mini"
                                   @click="() => remove(node, data)">
                          参数
                        </el-button>
                      </span>
                    </span>
                  </el-tree>
                </el-scrollbar>

              </el-card>
            </el-col>
            <el-col :span="4">
              <el-card shadow="never"
                       class="my-contain-card">
                <div style="margin: 80px auto; text-align: center">
                  <el-row style="margin-bottom: 10px; ">
                    <el-col :span="24">
                      <el-button plain
                                 icon="el-icon-folder-add"
                                 size="medium"
                                 :disabled="disableAddChildBtn"
                                 @click="addChildMenuNode">子级</el-button>
                    </el-col>
                  </el-row>
                  <el-row style="margin-bottom: 10px;">
                    <el-button plain
                               icon="el-icon-plus"
                               :disabled="disableSiblingBtn"
                               size="medium"
                               @click="addSiblingMenuNode">同级</el-button>
                  </el-row>
                  <el-row style="margin-bottom: 10px;">
                    <el-button plain
                               icon="el-icon-minus"
                               :disabled="! menuTreeNodeDeletable"
                               size="medium"
                               @click="deleteMenuNode">删除</el-button>
                  </el-row>
                </div>
              </el-card>
            </el-col>
            <el-col :span="10">
              <el-card shadow="never"
                       class="my-contain-card">
                <div slot="header"
                     class="clearfix">
                  <span>
                    <el-row>
                      <el-col :span="6">
                        备选项
                      </el-col>
                      <el-col :span="10">
                        <el-switch v-model="toggleIsPanel"
                                   active-text="面板"
                                   @change="swithChangeStatus"
                                   inactive-text="菜单组">
                        </el-switch>
                      </el-col>
                      <div v-if="! toggleIsPanel">
                        <el-col :span="4">
                          <el-button style="float: right; padding: 3px 3px"
                                     type="text"
                                     @click="dialogTableVisible = true">新增</el-button>
                        </el-col>
                        <el-col :span="4">
                          <el-button style="float: right; padding: 3px 3px"
                                     type="text">修改</el-button>
                        </el-col>
                      </div>
                    </el-row>
                    <el-dialog :visible.sync="dialogTableVisible"
                               title="新增菜单组">
                      <el-form :model="menuGroupForm"
                               :rules="rules"
                               ref="menuGroupForm"
                               label-width="100px">
                        <el-form-item label="菜单组标题"
                                      prop="title">
                          <el-input v-model="menuGroupForm.title"></el-input>
                        </el-form-item>
                        <el-form-item label="菜单组图标"
                                      prop="iconClass">
                          <el-input v-model="menuGroupForm.iconClass"
                                    :prefix-icon="menuGroupForm.iconClass"></el-input>
                        </el-form-item>
                        <el-form-item label="备注说明"
                                      prop="remark">
                          <el-input type="textarea"
                                    :rows="2"
                                    v-model="menuGroupForm.remark"></el-input>
                        </el-form-item>
                        <hr />
                        <el-form-item>
                          <el-button @click="resetForm('menuGroupForm')">重置</el-button>
                          <el-button type="primary"
                                     @click="submitForm('menuGroupForm')">提交保存</el-button>

                        </el-form-item>
                      </el-form>
                    </el-dialog>
                  </span>
                </div>
                <el-scrollbar style="height:580px">
                  <el-tree :data="rightTreeData"
                           style="height: 100%"
                           ref="rightTree"
                           show-checkbox
                           node-key="id"
                           :expand-on-click-node="false"
                           @check-change="getRightTreeCheckedKeys"
                           :check-strictly="true"
                           :props="rightTreeDefaultProps">

                  </el-tree>
                </el-scrollbar>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <div v-if="activeStep === 2">
          <el-row>
            <el-col :span="10">
              <el-card shadow="never"
                       class="my-contain-card">
                <div slot="header"
                     class="clearfix">
                  <span>
                    <el-row>
                      <el-col :span="12">
                        {{audit.leftTreeTitle}}
                      </el-col>
                      <el-col :span="12">
                        <el-button style="float: right; padding: 3px 5px"
                                   type="text"
                                   @click="handleParameterSetting(2)">参数配置</el-button>
                      </el-col>
                    </el-row>
                  </span>
                </div>
                <el-scrollbar style="height:580px">
                  <el-form :disabled="true">
                    <el-tree :data="audit.leftTreeData"
                             style="height: 100%"
                             :default-checked-keys="audit.leftTreeDataCheckedKeys"
                             show-checkbox
                             node-key="id"
                             :default-expand-all="true"
                             :check-strictly="true"
                             ref="auditLeftTree"
                             :props="defaultProps">
                      <span class="custom-tree-node"
                            slot-scope="{node,data}">
                        <span>
                          <i :class="data.iconClass"></i>
                          {{ node.label }}</span>
                        <!-- <span v-if="data.hasParameter === '1'"> -->
                        <span v-if="data.permType === '0' && data.parameters.length > 0 ">
                          <el-button type="text"
                                     size="mini"
                                     @click="() => remove(node, data)">
                            参数
                          </el-button>
                        </span>
                      </span>
                    </el-tree>
                  </el-form>
                </el-scrollbar>
              </el-card>
            </el-col>
            <el-col :span="4">
              <el-card shadow="never"
                       class="my-contain-card">
              </el-card>
            </el-col>
            <el-col :span="10">
              <el-card shadow="never"
                       class="my-contain-card">
                <div slot="header"
                     class="clearfix">
                  <span>
                    <el-row>
                      <el-col :span="12">
                        {{audit.rightTreeTitle}}
                      </el-col>
                      <el-col :span="12">
                        <el-button style="float: right; padding: 3px 5px"
                                   type="text"
                                   @click="handleParameterSetting(3)">参数配置</el-button>
                      </el-col>
                    </el-row>
                  </span>
                </div>
                <el-scrollbar style="height:580px">
                  <el-form :disabled="true">
                    <el-tree style="height: 100%"
                             :data="audit.rightTreeData"
                             :default-checked-keys="audit.rightTreeDataCheckedKeys"
                             ref="auditRightTree"
                             show-checkbox
                             node-key="id"
                             :default-expand-all="true"
                             :disabled="true"
                             :check-strictly="true"
                             :props="defaultProps">
                      <span class="custom-tree-node"
                            slot-scope="{node,data}">
                        <span>
                          <i :class="data.iconClass"></i>
                          {{ node.label }}</span>
                        <!-- <span v-if="data.hasParameter === '1'"> -->
                        <span v-if="data.permType === '0' && data.parameters.length > 0 ">
                          <el-button type="text"
                                     size="mini"
                                     @click="() => remove(node, data)">
                            参数
                          </el-button>
                        </span>
                      </span>
                    </el-tree>
                  </el-form>
                </el-scrollbar>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </transition>
    <el-card shadow="never">
      <el-table v-loading="listLoading"
                :data="dataList"
                border
                fit
                highlight-current-row
                style="width: 100%;">
        <el-table-column label="行号"
                         type="index"
                         sortable
                         align="center"
                         width="80">
        </el-table-column>
        <el-table-column label="角色名"
                         width="180px"
                         prop="title"
                         align="center">
        </el-table-column>
        <el-table-column label="审核状态"
                         width="80px"
                         align="center">
          <template slot-scope="{ row }">
            <span> {{ getDictLabel("audit_state", row.auditState)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注"
                         prop="remark"
                         align="left">
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         width="160px"
                         class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <el-tooltip v-if="hasPermission('/sysadmin/role/copy')"
                        class="item"
                        effect="light"
                        content="复制角色"
                        placement="top-start">
              <el-button :disabled="showDetail"
                         size="mini"
                         type="primary"
                         icon="el-icon-copy-document"
                         circle
                         @click="handleCopyNewRole(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip v-if="hasPermission('/sysadmin/role/update')"
                        class="item"
                        effect="light"
                        content="修改角色"
                        placement="top">
              <el-button :disabled="showDetail"
                         size="mini"
                         type="warning"
                         icon="el-icon-edit"
                         circle
                         @click="handleUpdate(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip v-if="hasPermission('/sysadmin/role/enable') || hasPermission('/sysadmin/role/disable')"
                        class="item"
                        effect="light"
                        content="禁用启用角色"
                        placement="top-end">
              <el-button :disabled="showDetail"
                         size="mini"
                         type="success"
                         icon="el-icon-s-check"
                         circle
                         @click="handleAudit(row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-el-drag-dialog
                 :visible.sync="dialogRoleDetailVisible"
                 title="复制角色">
        <el-form :model="roleDetailForm"
                 ref="roleDetailDialog"
                 label-width="100px">
          <el-form-item label="中文名称"
                        prop="title">
            <el-input v-model="roleDetailForm.title"></el-input>
          </el-form-item>
          <el-form-item label="备注说明"
                        prop="remark">
            <el-input type="textarea"
                      :rows="2"
                      v-model="roleDetailForm.remark"></el-input>
          </el-form-item>
          <hr />
          <el-form-item>
            <el-button @click="cancelRoleAddForm">取消</el-button>
            <el-button type="primary"
                       @click="handleRoleCopy">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import {  apiRoleList, apiListParameter, apiRoleDetail, apiMenuGroupList, apiRoleListPanel,
  apiRoleCreateMenuGroup, apiRoleCopy, apiRoleUpdate, apiRoleEnable, apiRoleDisable} from "@/api/sysadmin";
import { getLabel, getEntries, hasPermission } from "@/utils/dict";
import { getMenuTreeParameters } from "@/api/CommonUtil";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui

export default {
  name: "MandyRole",
  directives: { elDragDialog },
  data() {
    return {
      rules: {
        title: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
      },
      menuGroupForm: {
        id: 0,
        name: '',
        iconClass: '',
        remark: '',
      },
      roleDetailForm: {
        id: null,
        title: '',
        remark: '',
      },
      toggleIsPanel: true,
      //data: JSON.parse(JSON.stringify(data)), 
      defaultProps: {
        children: 'children',
        label: 'title',
      },
      rightTreeDefaultProps: {
        children: 'children',
        label: 'title',
        disabled: this.rightTreeNodeDisable,
      },

      dialogParameters: false,
      dialogParametersDisable: true,
      menuTreeData: [],
      mandyParameters: new Map(),
      menuTreeDataCheckedKeys: [],
      rightTreeData: [],
      rightTreeSelectedKeys: [],

      menuTreeCurrentNode: null,
      menuTreeChildrenAcceptable: true,
      menuTreeNodeDeletable: false,
      dialogTableVisible: false,
      dialogRoleDetailVisible: false,

      showDetail: false,
      activeStep: 1,
      dataList: null,
      currentRole: null,

      listLoading: false,
      listQuery: {
        auditState: undefined,
        title: undefined
      },

      audit: {
        leftTreeTitle: "",
        leftTreeData: [],
        leftTreeDataCheckedKeys: [],
        rightTreeData: [],
        rightTreeTitle: "",
        rightTreeDataCheckedKeys: [],
        rightShow: false
      },

      auditInit: {
        leftTreeTitle: "",
        leftTreeData: [],
        leftTreeDataCheckedKeys: [],
        rightTreeData: [],
        rightTreeTitle: "",
        rightTreeDataCheckedKeys: [],
        rightShow: false
      },

      blandNewRoleMenuNode: {
        permissionId: 0,
        permType: "",
        roleId: 0,
        remark: "",
        title: "",
        iconClass: "",
        parentId: 0,
        izAllowed: "",
        children: [],
        parameters: [],
        name: "",
        id: 0,
        permissionState: "",
        auditState: ""
      },

      auditTreeNodeDisable: true,
      rules: {
        title: [
          {
            required: true,
            message: "请输入面板标题",
            trigger: "blur"
          },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },

  //取回所有的角色及系统参数()
  created() {
    this.callRoleList();
    this.callListParameter();
  },

  watch: {
    // toggleIsPanel: {
    //   handler(newValue, oldValue) {
    //     this.rightTreeSelectedKeys = [];
    //     if (newValue) {
    //       this.callRoleListPanel();
    //     } else {
    //       this.callMenuGroupList();
    //     }
    //   },
    //   deep: false,
    //   immediate: true
    // },
  },

  computed: {
    actionTitle() {
      if (this.currentRole !== null) {
        return this.currentRole.title;
      }
      return "NULL";
    },

    disableAddChildBtn() {
      if (this.rightTreeSelectedKeys.length === 0) {
        return true;
      }

      if (this.menuTreeChildrenAcceptable) {
        return false;
      }

      return true;
    },

    disableSiblingBtn() {
      if (this.rightTreeSelectedKeys.length === 0) {
        return true;
      }

      if (this.menuTreeChildrenAcceptable) {
        return false;
      }

      if (this.menuTreeNodeDeletable) {
        return false;
      }

      return true;
    }

  },

  methods: {
    ...mapGetters([
      'dictMap'
    ]),

    messageSuccess() {
      this.$message({
        type: 'success',
        message: '提交成功!',
        duration: 3000
      });
    },

    hasPermission(url) {
      return hasPermission(url)
    },

    swithChangeStatus(newValue) {
      this.rightTreeSelectedKeys = [];
      if (newValue) {
        this.callRoleListPanel();
      } else {
        this.callMenuGroupList();
      }
    },

    handleParameterSetting(owner) {
      if (owner === 1) {
        this.dialogParametersDisable = false;
      } else if (owner === 2) {
        this.audit.ParameterOwner = 1;
        this.dialogParametersDisable = true;
      } else if (owner === 3) {
        this.audit.ParameterOwner = 2;
        this.dialogParametersDisable = true;
      }
      this.dialogParameters = true;
    },

    callGetMenuTreeParameters() {
      if (this.activeStep === 1) {
        return getMenuTreeParameters(this.menuTreeData);
      } else if (this.audit.ParameterOwner === 1) {
        return getMenuTreeParameters(this.audit.leftTreeData);
      } else {
        return getMenuTreeParameters(this.audit.rightTreeData);
      }
    },

    getOptions(dictKey) {
      return getEntries(dictKey);
    },

    getParameterOptions(parameterId) {
      let param = getLabel('mandy_param', parameterId + '');
      let ret = getEntries(param);
      return ret;
    },

    getDictLabel(dictKey, dictValue) {
      return getLabel(dictKey, dictValue);
    },

    getMenuCheckedKeys(treeData) {
      var ret = [];

      if (treeData === null || treeData.length === 0) {
        return ret;
      }

      for (let i = 0; i < treeData.length; i++) {
        if (treeData[i].izAllowed === "1") {
          ret.push(treeData[i].id);
          if (treeData[i].children && treeData[i].children.length > 0) {
            ret.push(...this.getMenuCheckedKeys(treeData[i].children));
          }
        }
      }
      return ret;
    },

    getRightTreeCheckedKeys() {
      this.rightTreeSelectedKeys = this.$refs.rightTree.getCheckedKeys();
    },

    rightTreeNodeDisable(data, node) {
      if (data.permType === '0') {
        return true;
      }
      return false;
    },

    quitEdit() {
      this.menuTreeChildrenAcceptable = true;
      this.menuTreeNodeDeletable = false;
      this.rightTreeSelectedKeys = [];
      this.showDetail = false;
      this.activeStep = 1;
    },

    handleDisableRole() {
      let infoMsg = "是否禁用当前角色:" + this.currentRole.title + " ？";

      this.$confirm(infoMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiRoleDisable(this.currentRole).then(response => {
          //const data = response.data;
          //更新一下数据
          this.callRoleList();
          this.showDetail = false;
          this.activeStep = 1;
          this.messageSuccess();
        });
      });
    },

    handleEnableRole(activeFlag) {
      let infoMsg = "";
      if (activeFlag == 1) {
        infoMsg = "是否给当前角色:" + this.currentRole.title + " 启用新的菜单权限？";
      } else {
        infoMsg = "是否启用当前角色:" + this.currentRole.title + " ？";
      }

      this.$confirm(infoMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiRoleEnable(this.currentRole).then(response => {
          //const data = response.data;
          //更新一下数据
          this.callRoleList();
          this.showDetail = false;
          this.activeStep = 1;
          this.messageSuccess();
        });
      });
    },

    syncMenuTreeDataCheckedNode(checkedKeys, list) {
      for (let i = 0; i < list.length; i++) {
        if (checkedKeys.includes(list[i].id)) {
          list[i].izAllowed = "1";
        } else {
          list[i].izAllowed = "0";
        }

        if (list[i].children && list[i].children.length > 0) {
          this.syncMenuTreeDataCheckedNode(checkedKeys, list[i].children)
        }
      }
    },

    commitNewCandidate() {
      let infoMsg = "是否确认给当前角色:" + this.currentRole.title + " 设置新的菜单权限？";
      if (this.currentRole.auditState === "1") {
        infoMsg += "\n 当前角色将变为 更新 状态！请及时审核！";
      }
      this.$confirm(infoMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //需要根据checkedKeys设置 izAllowed
        let checkedKeys = this.$refs.menuTree.getCheckedKeys();
        this.syncMenuTreeDataCheckedNode(checkedKeys, this.menuTreeData);
        apiRoleUpdate(this.menuTreeData).then(response => {
          const data = response.data;
          //更新角色列表, 有可能状态有更新
          this.showDetail = false;
          this.activeStep = 1;
          this.messageSuccess();
        }).catch((e) => { });;

      }).catch(() => { });
    },

    menuTreeCurrentChange(data, node) {
      if (data.permType === "2") {
        this.menuTreeChildrenAcceptable = true;
        this.menuTreeNodeDeletable = true;
      } else if (data.permType === "1") {
        this.menuTreeChildrenAcceptable = false;
        this.menuTreeNodeDeletable = true;
      } else {
        this.menuTreeChildrenAcceptable = false;
        this.menuTreeNodeDeletable = false;
      }
    },

    //数据库中的ID是自增的,为不与新生成的id冲突，临时ID采用负自增策略
    getMinId(tree) {
      let minId = -1;
      if (tree.length === 0) {
        return minId;
      }

      tree.forEach(element => {
        if (element.id < minId) {
          minId = element.id;
        }

        if (element.children) {
          let minChildId = this.getMinId(element.children);
          if (minChildId < minId) {
            minId = minChildId;
          }
        }
      });
      return minId;
    },

    createMenuNode(tree, parentId, element) {
      let minId = this.getMinId(this.$refs.menuTree.data);

      let newMenuNode = Object.assign({}, this.blandNewRoleMenuNode);
      //负自增
      newMenuNode.id = minId - 1;
      newMenuNode.parentId = parentId;

      newMenuNode.permissionId = element.id;
      newMenuNode.permType = element.permType;
      newMenuNode.title = element.title;
      newMenuNode.iconClass = element.iconClass;
      newMenuNode.remark = element.remark;
      newMenuNode.name = element.name;

      newMenuNode.roleId = this.currentRole.id;
      newMenuNode.auditState = "0";  // 
      newMenuNode.izAllowed = "0";
      newMenuNode.children = [];
      newMenuNode.parameters = element.parameters;
      tree.push(newMenuNode);

      return newMenuNode.id;
    },

    addMenuNode(menuList, parentId) {
      if (this.toggleIsPanel) { //加操作面板入菜单
        let checkedNodes = this.$refs.rightTree.getCheckedNodes();

        for (let i = 0; i < checkedNodes.length; i++) {
          let newParentId = this.createMenuNode(menuList, parentId, checkedNodes[i]);
          //加入面板下的功能
          let lastIdx = menuList.length - 1;
          let newChildren = menuList[lastIdx].children;
          for (let idx = 0; idx < checkedNodes[i].children.length; idx++) {
            this.createMenuNode(newChildren, newParentId, checkedNodes[i].children[idx]);
          }
        }
      } else { //加操作菜单组入菜单
        let checkedNodes = this.$refs.rightTree.getCheckedNodes();
        checkedNodes.forEach(element => {
          this.createMenuNode(menuList, parentId, element)
        });
      }
    },

    addFirstLevelMenuNode() {
      let menuList = this.$refs.menuTree.data;
      let parentId = 0;
      this.addMenuNode(menuList, parentId);
    },

    addSiblingMenuNode() {
      if (this.$refs.menuTree.getCurrentNode() === null) {
        this.addFirstLevelMenuNode();
      } else if (this.$refs.menuTree.currentNode.node.parent.data.children == undefined) {
        console.log("同级往上找父节点, 有可能没有父节点 二")
        this.addFirstLevelMenuNode();
      } else {
        console.log("同级往上找父节点, 有可能没有父节点 一")
        let menuList = this.$refs.menuTree.currentNode.node.parent.data.children;
        let parentId = this.$refs.menuTree.currentNode.node.parent.data.id;
        this.addMenuNode(menuList, parentId);
      }
    },

    addChildMenuNode() {
      if (this.$refs.menuTree.getCurrentNode() === null) {
        this.addFirstLevelMenuNode();
      } else {
        let menuList = this.$refs.menuTree.currentNode.node.data.children;
        let parentId = this.$refs.menuTree.currentNode.node.data.id;
        this.addMenuNode(menuList, parentId);
      }
    },

    deleteMenuNode() {
      if (this.$refs.menuTree.getCurrentNode() === null) {
        return;
      }

      let deleteId = this.$refs.menuTree.currentNode.node.data.id;
      console.log("deleteMenuNode 一 deleteId", deleteId);
      if (this.$refs.menuTree.currentNode.node.parent.data.children == undefined) {
        console.log("deleteMenuNode 2")
        const children = this.$refs.menuTree.data;
        const index = children.findIndex(d => d.id === deleteId);
        children.splice(index, 1);
      } else {
        console.log("deleteMenuNode 3")
        const children = this.$refs.menuTree.currentNode.node.parent.data.children;
        const index = children.findIndex(d => d.id === deleteId);
        children.splice(index, 1);
      }

    },

    callRoleCreateMenuGroup() {
      apiRoleCreateMenuGroup(this.menuGroupForm).then(response => {
        const data = response.data;
        this.rightTreeData.push(data);
        this.dialogTableVisible = false;
        this.messageSuccess();
      });
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.callRoleCreateMenuGroup();
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    userCancel() {
      this.$confirm('检测到有未保存的内容，是否在离开页面，放弃保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showDetail = false;
        this.activeStep = 1;
      });
    },

    handleDrag() {
      //this.$refs.select.blur()
    },

    nodeClick() {
      //
    },

    // 取回所有的面板, 备用项
    callRoleListPanel() {
      this.listLoading = true;
      apiRoleListPanel()
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.rightTreeData = data;
          }
        });
      this.listLoading = false;
    },

    // 取回所有的菜单组, 备用项
    callMenuGroupList() {
      this.listLoading = true;
      apiMenuGroupList()
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.rightTreeData = data;
          }
        });
      this.listLoading = false;
    },

    callRoleList() {
      this.listLoading = true;
      apiRoleList()
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.dataList = data;
          }
        });

      this.listLoading = false;
    },

    callListParameter() {
      this.listLoading = true;
      apiListParameter()
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            data.forEach(element => {
              this.mandyParameters.set(element.id, element);
            });
          }
        });
      this.listLoading = false;
    },

    getParameterTitle(pId) {
      if (this.mandyParameters.has(pId)) {
        let parameter = this.mandyParameters.get(pId);
        return parameter.title;
      }
      return '未定义';
    },

    getParameterDefaultValueLabel(pId) {
      if (this.mandyParameters.has(pId)) {
        let parameter = this.mandyParameters.get(pId);
        return this.getDictLabel(parameter.name, parameter.defaultValue);
      }
      return '未定义';
    },

    //分三种情况处理
    // 一、角色状态是 禁用 （a. 当前角色待启用的菜单）
    //        操作有: A 启用角色  角色状态转为 启用
    // 二、角色状态是 更新 即角色已启用, 有菜单变更 （a. 当前角色禁用（待启用）的菜单, b. 当前角色在用的菜单） 
    //        操作有:  A. 启用菜单, 即将b删除, a 更新为在用。 角色状态转为 启用
    //                B. 禁用角色  角色状态转为 禁用, a 会被删除, b 转为禁用
    // 三、角色状态是 启用 (b. 当前角色在用的菜单)
    //        操作有: A. 禁用角色  角色状态转为 禁用, b 转为禁用
    handleAudit(row) {
      if (this.showDetail) {
        this.$alert('请先提交或取消当前操作', '提示', {
          confirmButtonText: '确定',
          callback: action => { }
        });
        return;
      }

      this.menuTreeData = [];
      this.menuTreeDataCheckedKeys = [];
      //getRoleMenuPermList(row) {
      this.listLoading = true;
      this.audit = Object.assign({}, this.auditInit);

      apiRoleDetail(row.id)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.currentRole = data.mandyRole;
            if (this.currentRole.auditState === "0") {
              this.audit.leftTreeTitle = "待启用菜单"
              this.audit.leftTreeData = data.newCandidate;
              this.audit.leftTreeDataCheckedKeys = this.getMenuCheckedKeys(this.audit.leftTreeData);
              this.audit.rightShow = false;
              this.audit.rightTreeTitle = "暂无数据"
            } else if (this.currentRole.auditState === "1") {
              this.audit.leftTreeTitle = "当前使用菜单"
              this.audit.leftTreeData = data.inUsed;
              this.audit.leftTreeDataCheckedKeys = this.getMenuCheckedKeys(this.audit.leftTreeData);
              this.audit.rightShow = false;
              this.audit.rightTreeTitle = "暂无数据"
            } else {  // if (this.currentRole.auditState === "2")
              this.audit.leftTreeTitle = "待启用菜单"
              this.audit.leftTreeData = data.newCandidate;
              this.audit.leftTreeDataCheckedKeys = this.getMenuCheckedKeys(this.audit.leftTreeData);
              this.audit.rightTreeData = data.inUsed;
              this.audit.rightTreeTitle = "当前使用菜单"
              this.audit.rightTreeDataCheckedKeys = this.getMenuCheckedKeys(this.audit.rightTreeData);
              this.audit.rightShow = true;
            }
            this.showDetail = true;
            this.activeStep = 2;
          }
        });
      this.listLoading = false;
    },

    handleUpdate(row) {
      if (this.showDetail) {
        this.$alert('请先提交或取消当前操作', '提示', {
          confirmButtonText: '确定',
          callback: action => { }
        });
        return;
      }

      this.menuTreeData = [];
      this.menuTreeDataCheckedKeys = [];
      //getRoleMenuPermList(row) {
      this.listLoading = true;

      apiRoleDetail(row.id)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.currentRole = data.mandyRole;
            if (this.currentRole.auditState === "0") {
              this.menuTreeData = data.newCandidate;
            } else if (this.currentRole.auditState === "1") {
              this.menuTreeData = data.inUsed;
            } else { //if(this.currentRole.auditState ==="2")
              this.menuTreeData = data.newCandidate;
            }
            this.menuTreeDataCheckedKeys = this.getMenuCheckedKeys(this.menuTreeData);
            //this.menuTreeDataCheckedKeys = [1, 2, 3, 4]
            //this.currentRole = row;
            this.showDetail = true;
            this.activeStep = 1;
          }
        });
      this.listLoading = false;
    },


    getStateLabel(state) {
      return getDictLabel('audit_state', state);
    },


    handleFilter() { },

    // dialogRoleDetailVisible
    handleCopyNewRole(row) {
      this.roleDetailForm.id = row.id;
      this.roleDetailForm.title = row.title;
      this.roleDetailForm.remark = row.remark;
      this.dialogRoleDetailVisible = true;
    },

    handleRoleCopy() {
      apiRoleCopy(this.roleDetailForm).then(response => {
        this.showDetail = false;
        const data = response.data;
        this.dataList.push(data);
        this.dialogRoleDetailVisible = false;

        this.messageSuccess();
      }).catch((e) => {
        this.dialogRoleDetailVisible = true;
      });
    },

    cancelRoleAddForm() {
      this.dialogRoleDetailVisible = false;
      this.showDetail = false;
    },
  }
};
</script>
<style scoped>
.el-scrollbar {
  height: 100%;
}

.my-contain-card {
  padding: 2px;
  width: 100%;
  height: 650px;
  vertical-align: middle;
}

.el-tree {
  width: 100%;
  height: 100%;
  min-width: 100%;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-form-item-param {
  margin-bottom: 12px;
}

.el-card-param /deep/ .el-card__body {
  padding: 6px;
}
.el-card-param /deep/ .el-card__header {
  padding: 8px 20px;
  border-bottom: 1px solid #ebeef5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  font-size: 16px;
  /* background-color: lightgrey; */
}
</style>



